package client.pqueue;

import java.net.InetSocketAddress;

import org.apache.mina.core.RuntimeIoException;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.json.JSONException;
import org.json.JSONObject;

import funcs.mina.codec.TextLineCodecFactory;

public class QClient {

	private String host = "127.0.0.1";
	private int port = 12800;
	private long timeout = 30 * 1000L; // 30 seconds
	private static IoSession session;

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public long getTimeout() {
		return timeout;
	}

	public void setTimeout(long timeout) {
		this.timeout = timeout;
	}

	public void close() {

	}

	public void init() {
		try {
			if (session == null || !session.isConnected()) {
				connect(host, port, timeout);
			}
		} catch (Exception ex) {

		}
	}

	public static void connect(String sHost, int sPort, long sTimeout)
			throws InterruptedException {
		System.out.println("connect to " + sHost + ":" + sPort);

		NioSocketConnector connector = new NioSocketConnector();
		// Configure the service.
		connector.setConnectTimeoutMillis(sTimeout);
		connector.getFilterChain().addLast("codec",
				new ProtocolCodecFilter(new TextLineCodecFactory()));
		connector.getFilterChain().addLast("logger", new LoggingFilter());
		connector.setHandler(new QClientHandler(sHost, sPort, sTimeout));

		for (;;) {
			try {
				ConnectFuture future = connector.connect(new InetSocketAddress(
						sHost, sPort));
				future.awaitUninterruptibly();
				session = future.getSession();
				break;
			} catch (RuntimeIoException e) {
				System.err.println("Failed to connect.");
				e.printStackTrace();
				Thread.sleep(5000);
			}
		}

		// wait until the summation is done
		// session.getCloseFuture().awaitUninterruptibly();
		// connector.dispose();
	}

	/**
	 * 发送消息
	 * 
	 * @param msg
	 * @return
	 */
	public boolean send(String opt, String auth, String key, JSONObject data) {
		if (session == null) {
			return false;
		}
		if (session.isConnected()) {
			try {
				JSONObject optJson = new JSONObject();
				optJson.put("o", opt);
				optJson.put("a", auth);
				optJson.put("d", data);

				StringBuffer cmd = new StringBuffer();
				cmd.append(key);
				cmd.append(" ");
				cmd.append(optJson.toString());

				String message = cmd.toString();
				session.write(message);

				System.out.println(message);
				return true;
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		return false;
	}
}
